CC=gcc
CFLAGS=-Wall -g
CFLAGS_PIC=-fPIC
INCLUDES=-I. -Iinc/
LFLAGS=-L.
SO_FLAGS=-shared -W1,-soname,lib
LIBS=
OBJDIR=obj
SRCDIR=src
VERSION=1
MAIN=maylloc
BENCHMARKS=benchmarks
BENCHMARK_LIBS=libmmutil.a
BENCHMARK_INC=-I$(BENCHMARKS)/inc
TEX_FILE=ProjectReport
BIB_FILE=bib.bib

OBJFILES := $(patsubst $(SRCDIR)/%.c,$(OBJDIR)/%.o,$(wildcard $(SRCDIR)/*.c))

TESTDIR=tests
TESTOBJS := $(patsubst $(TESTDIR)/%.c,$(OBJDIR)/$(TESTDIR)/%.o,$(wildcard $(TESTDIR)/*.c))
TEST=test

THREADTEST=threadtest
THREADTESTOBJS= $(patsubst $(BENCHMARKS)/$(THREADTEST)/%.c,$(OBJDIR)/$(THREADTEST)/%.o,$(wildcard $(BENCHMARKS)/$(THREADTEST)/*.c))

LARSON=larson
LARSONOBJS= $(patsubst $(BENCHMARKS)/$(LARSON)/%.c,$(OBJDIR)/$(LARSON)/%.o,$(wildcard $(BENCHMARKS)/$(LARSON)/*.c))

all:  $(OBJDIR) $(MAIN) $(TEST) $(THREADTEST) $(LARSON) $(TEX_FILE).pdf

#Create required directories.
$(OBJDIR):
	@mkdir -p $@
	@mkdir -p $@/$(TESTDIR)
	@mkdir -p $@/$(THREADTEST)
	@mkdir -p $@/$(LARSON)
	@mkdir -p $@/$(CACHESCRATCH)
	@mkdir -p $@/$(CACHETHRASH)

#Generates object files from source files.
$(OBJDIR)/%.o: $(SRCDIR)/%.c
	$(CC) $(CFLAGS_PIC) $(CFLAGS) $(INCLUDES) -c -o $@ $<

$(OBJDIR)/$(TESTDIR)/%.o: $(TESTDIR)/*.c
	$(CC) $(CFLAGS) $(INCLUDES) -c -o $@ $<

$(OBJDIR)/$(THREADTEST)/%.o: $(BENCHMARKS)/$(THREADTEST)/*.c
	$(CC) $(CFLAGS) $(INCLUDES) $(BENCHMARK_INC) -c -o $@ $<

$(OBJDIR)/$(LARSON)/%.o: $(BENCHMARKS)/$(LARSON)/*.c
	$(CC) $(CFLAGS) $(INCLUDES) $(BENCHMARK_INC) -c -o $@ $<

$(TEST): $(TESTOBJS)
	$(CC) $(CFLAGS) -o $@ $? $(LFLAGS) $(LIBS) -lmaylloc -lpthread

$(THREADTEST): $(THREADTESTOBJS)
	$(CC) $(CFLAGS) -o $@ $? $(BENCHMARK_LIBS) $(LFLAGS) $(LIBS) -lpthread

$(LARSON): $(LARSONOBJS)
	$(CC) $(CFLAGS) -o $@ $? $(BENCHMARK_LIBS) $(LFLAGS) $(LIBS) -lpthread

$(MAIN): $(OBJFILES)
	ar  rcs lib$(MAIN).a $(OBJFILES)
	$(CC) $(CFLAGS) $(INCLUDES) $(SO_FLAGS)$@.so.$(VERSION) -o lib$(MAIN).so.$(VERSION) $? $(LFLAGS) $(LIBS)

$(TEX_FILE).pdf: $(TEX_FILE).tex $(BIB_FILE)
	pdflatex --shell-escape $(TEX_FILE).tex
	bibtex $(TEX_FILE).aux
	pdflatex --shell-escape $(TEX_FILE).tex
	pdflatex --shell-escape $(TEX_FILE).tex

clean:
	rm -rf $(OBJDIR)
	rm -f lib$(MAIN).*
	rm -f $(TEST)
	rm -f a.out
	rm -f $(TEX_FILE).aux
	rm -f $(TEX_FILE).bbl
	rm -f $(TEX_FILE).log
	rm -f $(TEX_FILE).blg
	rm -f $(TEX_FILE).out
	rm -f $(THREADTEST)
	rm -f $(LARSON)
	rm -f *-converted-to.pdf
